﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SbsSW.SwiPlCs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Adventure.Model
{
    internal class Gate
    {
        #region Constructors

        internal Gate(Rectangle bounds, string name)
        {
            _bounds = bounds;
            _name = name;
        }

        #endregion

        #region Private Fields

        private string _name;
        private Rectangle _bounds;
        private Texture2D _texture;
        private Texture2D _textureOpen;
        private int _lastUpdateTime = 0;
        private bool _open = false;

        #endregion

        #region Internal Methods

        internal void Initialize()
        {
            _texture = GraphicsResources.ContentManager.Load<Texture2D>(@"Textures\Gate");
            _textureOpen = GraphicsResources.ContentManager.Load<Texture2D>(@"Textures\GateOpen");
        }

        internal void Draw(GameTime gameTime)
        {
            GraphicsResources.SpriteBatch.Begin();
            GraphicsResources.SpriteBatch.Draw(_open ? _textureOpen : _texture, _bounds, Color.White);
            GraphicsResources.SpriteBatch.End();
        }

        internal void Update(GameTime gameTime, int time)
        {
            using (var openQuery = new PlQuery(string.Format("aberto({0}, {1}, S)", _name, time)))
            {
                var open = openQuery.SolutionVariables.First();
                _open = open["S"].ToString() == "1" ? true : false;
            }
        }

        internal void UpdateData(int time)
        {
            PlQuery.PlCall(string.Format("retract(aberto({0}, {1}, {2}))", _name, _lastUpdateTime, _open ? "1" : "0"));
            PlQuery.PlCall(string.Format("asserta(aberto({0}, {1}, {2}))", _name, time, _open ? "1" : "0"));

            _lastUpdateTime = time;
        }

        #endregion
    }
}
